# -*- coding: utf-8 -*-

import os
import shutil
import gzip

from jsc import xxtea

def get_filePath_fileName_fileExt(fileUrl):
    """
    获取文件路径， 文件名， 后缀名
    :param fileUrl:
    :return:
    """
    filepath, tmpfilename = os.path.split(fileUrl)
    shotname, extension = os.path.splitext(tmpfilename)
    return filepath, shotname, extension

def write_content_to_file(file_name, content):
    file_ob = open(file_name, 'wb')
    file_ob.write(content)
    file_ob.close()


def read_file_content(file_name):
    file_ob = open(file_name, 'rb')
    content = file_ob.read()
    file_ob.close()
    return content


def zip_file(file_name, file_name_in_zip, zip_file_name):
    f_in = open(file_name, 'rb')
    f_out = gzip.open(zip_file_name, 'wb')
    f_out.writelines(f_in)
    f_out.close()
    f_in.close()


def unzip_file(file_name, target_dir):
    f_in = gzip.open(file_name, 'rb')
    f_out = open(target_dir + '/encrypt.js', 'wb')
    file_content = f_in.read()
    f_out.write(file_content)
    f_out.close()
    f_in.close()
    return True


def decrypt(is_zip, input_key, input_jsc_path):
    print('开始解密')
    prefix = 'decryptOutput'

    jsc_path = input_jsc_path
    if jsc_path == '':
        jsc_path = input('请输入你的.jsc文件路径:')

    if os.path.exists(jsc_path) is False:
        print("错误: 你输入的.jsb文件不存在")
        return False

    key = input_key
    if key == '':
        key = input('请输入你的密钥:')

    if key == '':
        print("错误: 你输入的密钥为空")
        return False

    enc_file_content = read_file_content(jsc_path)
    dec = xxtea.decrypt(enc_file_content, key.encode())
    des_file_name = prefix + '/dec.js'
    if os.path.exists(des_file_name) is True:
        os.remove(des_file_name)

    if os.path.exists(prefix) is False:
        os.mkdir(prefix)
    write_content_to_file(des_file_name, dec)

    decrypt_file_name = prefix + '/' + get_filePath_fileName_fileExt(jsc_path)[-2] + '.js'
    if os.path.exists(decrypt_file_name) is True:
        os.remove(decrypt_file_name)

    if is_zip is True:
        print('开始解压')
        isUnzipSuc = unzip_file(des_file_name, prefix)
        os.remove(des_file_name)
        if isUnzipSuc is False:
            return False
        else:
            os.rename(prefix + '/encrypt.js', decrypt_file_name)
    else:
        os.rename(des_file_name, decrypt_file_name)

    print("success. please check 'decryptOutput' directory.")
    print('> note: if your decrypt.js is 0b,',)
    print('please confirm your zip option and your decrypt key is right.')
    return True

def encrypt(is_zip, input_key, input_js_path):
    print('开始执行文件加密')

    js_path = input_js_path
    if js_path == '':
        js_path = input('请输入你的.js文件路径:')

    if os.path.exists(js_path) is False:
        print("错误: 你的.js文件不存在")
        return False

    key = input_key
    if key == '':
        key = input('请输入你的密钥:')

    if key == '':
        print("错误: 你输入的密钥为空")
        return False

    output_file_name = get_filePath_fileName_fileExt(js_path)[-2]

    prefix = 'encryptTemp'
    if os.path.exists(prefix) is True:
        shutil.rmtree(prefix)
    os.mkdir(prefix)

    output = 'encryptOutput'
    if os.path.exists(output) is True:
        shutil.rmtree(output)
    os.mkdir(output)

    # zip .jsc
    if is_zip is True:
        print('开始压缩.js文件')
        project_zip_name = prefix + '/' + output_file_name + '.zip'
        shutil.copy(js_path, prefix + '/' + output_file_name + '.js')
        zip_file(prefix + '/' + output_file_name + '.js', '', project_zip_name)
        project_content = read_file_content(project_zip_name)
    else:
        project_content = read_file_content(js_path)
    # encrypt
    print('开始加密')
    enc = xxtea.encrypt(project_content, key.encode())
    final_jsc_name = prefix + '/' + output_file_name + '.jsc'
    write_content_to_file(final_jsc_name, enc)

    shutil.copy(final_jsc_name, output + '/' + output_file_name + '.jsc')

    print('删除临时目录')
    if os.path.exists(prefix) is True:
        shutil.rmtree(prefix)
    print("成功，请查看'encryptOutput'目录")
    return True

if __name__ == "__main__":
    # decrypt(True, '7e49b183-e160-42', 'project.jsc')
    encrypt(True, '7e49b183-e160-42', 'decryptOutput/project.js')

